package com.katze.common.controller;

import cn.idev.excel.FastExcel;
import cn.idev.excel.write.builder.ExcelWriterBuilder;
import cn.idev.excel.write.metadata.style.WriteCellStyle;
import cn.idev.excel.write.metadata.style.WriteFont;
import cn.idev.excel.write.style.HorizontalCellStyleStrategy;
import cn.idev.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.katze.common.Message;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//todo
public abstract class BaseController {

    /**
     * 表格数据格式
     * @param pageInfo 数据集
     * @return 表格数据
     */
    protected Message toDataTable(Object pageInfo) {
        Map<String, Object> rspData = new HashMap<>();
        if (pageInfo instanceof IPage){
            rspData.put("rows", ((IPage<?>) pageInfo).getRecords());
            rspData.put("total", ((IPage<?>) pageInfo).getTotal());
        } else if (pageInfo instanceof List) {
            rspData.put("rows", pageInfo);
            rspData.put("total", ((List<?>) pageInfo).size());
        } else {
            rspData.put("rows", new ArrayList<>());
            rspData.put("total", 0);
        }
        return Message.ok().data(rspData);
    }


    public void downXlsx(String name, List<?> data, HttpServletResponse response) throws IOException {
        if (data != null && !data.isEmpty()){
            Class<?> cs = data.getFirst().getClass();
            response.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Access-Control-Expose-Headers", "Content-Filename");
            response.setHeader("Content-Filename", URLEncoder.encode(name.concat(".xlsx"), StandardCharsets.UTF_8));

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 背景设置为红色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headWriteCellStyle.setWriteFont(new WriteFont());
            headWriteCellStyle.getWriteFont().setFontHeightInPoints((short) 12);

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            contentWriteCellStyle.setWriteFont(new WriteFont());

            ExcelWriterBuilder builder = FastExcel.write(response.getOutputStream(), cs)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
            builder.sheet().doWrite(data);
        }
    }
}
